/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.commons.core;

import cn.seaboot.commons.file.ReaderUtils;
import cn.seaboot.commons.lang.P;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * FastJson工具类
 *
 * <p>
 * //输出空置字段
 * JSONWriter.Feature.WriteMapNullValue,
 * //list字段如果为null，输出为[]，而不是null
 * JSONWriter.Feature.WriteNullListAsEmpty,
 * //相同数据不进行引用
 * JSONWriter.Feature.DisableCircularReferenceDetect
 * //IE6兼容，进行中文编码
 * JSONWriter.Feature.BrowserCompatible,
 * // 数值字段如果为null，输出为0，而不是null
 * JSONWriter.Feature.WriteNullNumberAsZero,
 * // Boolean字段如果为null，输出为false，而不是null
 * JSONWriter.Feature.WriteNullBooleanAsFalse,
 * // 字符类型字段如果为null，输出为""，而不是null
 * JSONWriter.Feature.WriteNullStringAsEmpty,
 * <p>
 * <p>
 * 2019/10/16 上午11:08       v2  优化日期序列化
 *
 * @author Mr.css
 * @version 2023-09-13 10:41 升级到 fastjson2
 * @since fastjson2
 */
public class FastJsonUtils {

    private static final JSONWriter.Context context;

    static {
        context = new JSONWriter.Context();

        // 时区/日期格式化
        context.setZoneId(P.zoneId());
        context.setDateFormat(P.DATE_FORMAT_DATETIME);
    }

    private FastJsonUtils() {
    }

    public static JSONWriter.Context getContext() {
        return context;
    }

    /**
     * 构造一个JSON串
     *
     * @param objs 键值数组
     * @return json
     */
    public static String makeJson(Object... objs) {
        if (objs == null) {
            return "{}";
        }
        if (objs.length % 2 != 0) {
            throw new IllegalArgumentException("array length must be a multiple of 2");
        }
        JSONObject json = new JSONObject(objs.length / 2);
        for (int i = 0; i < objs.length; i++) {
            json.put(objs[i++].toString(), objs[i]);
        }
        return json.toJSONString();
    }

    /**
     * 使用全局配置，对象转json
     *
     * @param object 对象
     * @return json
     */
    public static String toJSONString(Object object) {
        return JSON.toJSONString(object, context);
    }

    /**
     * 使用全局配置，对象转json
     *
     * @param object 对象
     * @return json
     */
    public static byte[] toJSONBytes(Object object) {
        return JSON.toJSONBytes(object);
    }

    /**
     * json转对象
     *
     * @param json json
     * @return o
     */
    public static Object parse(String json) {
        return JSON.parse(json);
    }

    /**
     * json转对象
     *
     * @param json  json
     * @param clazz 目标对象类型
     * @return o
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }

    /**
     * json转对象
     *
     * @param is    输入流
     * @param clazz 目标对象类型
     * @return o
     */
    public static <T> T parseObject(InputStream is, Class<T> clazz) {
        return JSON.parseObject(is, clazz);
    }

    /**
     * json 转 List
     *
     * @param json  json
     * @param clazz 目标对象类型
     * @return o
     */
    public static <T> List<T> parseArray(String json, Class<T> clazz) {
        return JSON.parseArray(json, clazz);
    }

    /**
     * json 转 List
     *
     * @param is    输入流
     * @param clazz 目标对象类型
     * @return o
     */
    public static <T> List<T> parseArray(InputStream is, Class<T> clazz) throws IOException {
        byte[] bytes = ReaderUtils.readAsByteArray(is);
        return JSON.parseArray(bytes, clazz);
    }

    /**
     * json 转 ListMap
     * <p>
     * JSONArray 的本质就是 ListMap
     *
     * @param json json
     * @return o
     */
    @SuppressWarnings("rawtypes")
    public static List<Map> parseListMap(String json) {
        return JSONArray.parseArray(json, Map.class);
    }

    /**
     * json 转 JSONObject
     *
     * @param json json
     * @return o
     */
    public static JSONObject toJSONObject(String json) {
        return JSONObject.parseObject(json);
    }

    /**
     * Object 转 JSONObject
     *
     * @param obj obj
     * @return o
     */
    public static JSONObject toJSONObject(Object obj) {
        return (JSONObject) JSON.toJSON(obj);
    }

    /**
     * json 转 JSONArray
     *
     * @param json json
     * @return o
     */
    public static JSONArray toJSONArray(String json) {
        return JSONArray.parse(json);
    }

    /**
     * Object 转 JSONArray
     *
     * @param obj obj
     * @return o
     */
    public static JSONArray toJSONArray(Object obj) {
        return (JSONArray) JSON.toJSON(obj);
    }

    /**
     * 集合 转 JSONArray
     *
     * @param collection obj
     * @return o
     */
    public static JSONArray toJSONArray(@SuppressWarnings("rawtypes") Collection collection) {
        return JSONArray.from(collection);
    }
}
